/**
 * 安卓白金英雄坛制作组 <br>
 * 文件名：BLGMusic.java <br>
 * 创建时间：2014-8-13 上午11:39:30 <br>
 * 所属项目：GmudEX <br>
 * @author 12548 <br>
 */
package lostland.gmud.exv2.blgframework.impl;

import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;

import java.io.IOException;

import lostland.gmud.exv2.blgframework.Music;

/**
 * 类名：BLGMusic <br>
 * 说明：
 *
 * @author 12548
 */
public class BLGMusic implements Music, OnCompletionListener {

	MediaPlayer mediaPlayer;
	boolean isPrepared = false;

	/**
	 * @param assetDescriptor
	 */
	public BLGMusic(AssetFileDescriptor assetDescriptor) {
		mediaPlayer = new MediaPlayer();
		try {
			mediaPlayer.setDataSource(assetDescriptor.getFileDescriptor(),
					assetDescriptor.getStartOffset(),
					assetDescriptor.getLength());
			mediaPlayer.prepare();
			isPrepared = true;
			mediaPlayer.setOnCompletionListener(this);
		} catch (Exception e) {
			throw new RuntimeException("Couldn't load music");
		}
	}

	/* （非 Javadoc）
	 * @see lostland.gmud.exv2.blgframework.Music#play()
	 */
	@Override
	public void play() {
		if (mediaPlayer.isPlaying())
			return;
		try {
			synchronized (this) {
				if (!isPrepared)
					mediaPlayer.prepare();
				mediaPlayer.start();
			}
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/* （非 Javadoc）
	 * @see lostland.gmud.exv2.blgframework.Music#stop()
	 */
	@Override
	public void stop() {
		if (mediaPlayer.isPlaying())
			mediaPlayer.stop();
	}

	/* （非 Javadoc）
	 * @see lostland.gmud.exv2.blgframework.Music#pause()
	 */
	@Override
	public void pause() {
		if (mediaPlayer.isPlaying())
			mediaPlayer.pause();
	}

	/* （非 Javadoc）
	 * @see lostland.gmud.exv2.blgframework.Music#setLooping(boolean)
	 */
	@Override
	public void setLooping(boolean isLooping) {
		mediaPlayer.setLooping(isLooping);
	}

	/* （非 Javadoc）
	 * @see lostland.gmud.exv2.blgframework.Music#setVolume(float)
	 */
	@Override
	public void setVolume(float volume) {
		mediaPlayer.setVolume(volume, volume);
	}


	@Override
	public boolean isLooping() {
		return mediaPlayer.isLooping();
	}

	@Override
	public boolean isPlaying() {
		return mediaPlayer.isPlaying();
	}

	@Override
	public boolean isStopped() {
		return !isPrepared;
	}


	/* （非 Javadoc）
	 * @see lostland.gmud.exv2.blgframework.Music#dispose()
	 */
	@Override
	public void dispose() {
		if (mediaPlayer.isPlaying())
			mediaPlayer.stop();
		mediaPlayer.release();
	}

	/* （非 Javadoc）
	 * @see android.media.MediaPlayer.OnCompletionListener#onCompletion(android.media.MediaPlayer)
	 */
	@Override
	public void onCompletion(MediaPlayer arg0) {
		synchronized (this) {
			isPrepared = false;
		}
	}

}
